/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatclient;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author isen
 */
public class ServerConnection {

    Socket socket;
    PrintWriter writeStringOnSocket;
    BufferedReader readStringFromSocket;
    boolean loggedIn = false;
    
    boolean isConnected() {
        return socket.isConnected();
    }
    
    public ServerConnection(String host, int port) {
        try {
            socket = new Socket(host, port);
            writeStringOnSocket = new PrintWriter(
                    new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            readStringFromSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException ex) {
            Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public boolean login(String username, String password) throws IOException {
        writeLine("login "+username+" "+password);
        loggedIn = readLine().equals("loggedIn");
        return loggedIn;
    }

    public boolean createAccount(String username, String password, String name, String email) {
        //writeLine("create "+ username +" "+ password+" "+name+ " "+email);
        writeLine(String.format("create %s %s %s %s",username,password,name,email));
        return readLine().equals("success");
    }
    
    public boolean usernameExists(String username){
        writeLine("usernameExists "+ username);
        return readLine().equals("used");
    }

    public void writeLine(String line) {
        writeStringOnSocket.println(line);
        writeStringOnSocket.flush();
    }

    public String readLine(){
        try {
            return readStringFromSocket.readLine();
        } catch (IOException ex) {
            Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }
}
